package org.halk.httpserver;

import org.halk.httpserver.entity.Request;
import org.halk.httpserver.entity.Response;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 简单web服务实现
 * 使用 ServerSocket 监听指定端口（8181）
 * Request 类处理HTTP请求解析
 * Response 类负责发送静态资源
 * 采用阻塞式I/O模型
 *
 * @Author zhuhao
 * @Date 2022/5/26 17:17
 * @desc
 */
public class HttpServer {

    public static void main(String[] args) {
        HttpServer httpServer = new HttpServer();
        httpServer.await();
    }

    public void await() {
        int port = 8181;
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        System.out.println("服务器启动，监听端口：" + port);

        //循环等待一个request请求
        while (true) {
            Socket socket;
            InputStream inputStream;
            OutputStream outputStream;
            try {
                //创建socket
                socket = serverSocket.accept();
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();

                //封装input至request，并处理请求
                Request request = new Request(inputStream);
                request.parse();

                //封装output至response
                Response response = new Response(outputStream);
                response.setRequest(request);
                response.sendStaticResource();

                //关闭socket
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
